package com.itheima.service.impl;

import com.itheima.mapper.MeteorologyMapper;
import com.itheima.pojo.Meteorology;
import com.itheima.service.MeteorologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Service
public class MeteorologyServiceImpl implements MeteorologyService {
    @Autowired
    private MeteorologyMapper meteorologyMapper;

    @Override
    public void add(Meteorology meteorology) {
        meteorologyMapper.add(meteorology);
    }

    @Override
    public List<Meteorology> findMeteorologyByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        List<Meteorology> meteorologyList= meteorologyMapper.findMeteorologyByTimeRange(startTime,endTime);
        return meteorologyList;
    }

    @Override
    public Meteorology findMeteorologyByTimestamp(LocalDateTime TimeStamp) {
        Meteorology meteorology = meteorologyMapper.findMeteorologyByTimestamp(TimeStamp);
        return meteorology;
    }
    @Override
    public Meteorology findMeteorologyByUserSelectSingleTimeStamp(LocalDateTime TimeStamp) {
        // 数据每半个小时一条，首先将数据转化为距离该时间戳最近的数据节点
        // 例如：2025-02-09 03:01:00 转化为 2025-02-09 03:00:00
        //      2025-02-09 03:29:00 转化为 2025-02-09 03:00:00
        //      2025-02-09 03:31:00 转化为 2025-02-09 03:30:00

        // 获取输入时间戳的分钟数
        int minute = TimeStamp.getMinute();

        // 计算最近的时间节点
        LocalDateTime newTimeStamp;
        if (minute < 15) {
            // 如果分钟数小于15，则归到当前小时的00分
            newTimeStamp = TimeStamp.withMinute(0).withSecond(0).withNano(0);
        } else if (minute < 45) {
            // 如果分钟数在15到44之间，则归到当前小时的30分
            newTimeStamp = TimeStamp.withMinute(30).withSecond(0).withNano(0);
        } else {
            // 如果分钟数大于等于45，则归到下一小时的00分
            newTimeStamp = TimeStamp.plusHours(1).withMinute(0).withSecond(0).withNano(0);
        }

        // 然后再通过该节点查询数据
        Meteorology meteorology = meteorologyMapper.findMeteorologyByTimestamp(newTimeStamp);

        return meteorology;
    }

    @Override
    public Meteorology findLatestMeteorology() {
        Meteorology latestMeteorology = meteorologyMapper.findLatestMeteorology();
        return latestMeteorology;
    }

    @Override
    public List<Meteorology> findMeteorologyInLatestDayData() {
        List<Meteorology> meteorologyList = meteorologyMapper.findMeteorologyInLatestDayData();
        return meteorologyList;
    }

    @Override
    public Integer findMeteorologyAllNumber(){
        Integer meteorologyNumber = meteorologyMapper.findMeteorologyAllNumber();
        return meteorologyNumber;
    }
}
